package com.zsy.filter;

import com.zsy.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-11 20:23
 **/
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求路径
        String url = request.getRequestURL().toString();
        // 1.判断请求路径是否包含"/login"
        if (url.contains("/login")) {
            // 2.包含直接放行
            filterChain.doFilter(request, response);
            return;
        }
        // 3.不包含判断token
        // 从请求头获取token
        String token = request.getHeader("token");
        // 1.解析token
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            // 2.解析不通过 直接返回401
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        // 4.通过直接放行
        log.info("令牌合法, 放行");
        filterChain.doFilter(request, response);
    }
}
